<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ include file="/WEB-INF/jsp/include/taglibs.jsp"%>
<%-- basheers code added by srikanth start --%>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/rateTableForQGL.js" ></script>
<script type="text/javascript">
var actualUserId = '${actionBean.userId}';
var jobId = ${actionBean.invoice.job.jobId};
var rateitemcount = 0;
var reqrtcodes = [];
        var agencies = [

            <c:forEach items="${actionBean.agencies}" var="agency" varStatus="agencyStatus">
            {
                value:"${agency.userId} ${agency.initials} ${agency.firstName} ${agency.lastName}",
                id: "${agency.userId}",
                initial: "${agency.initials}",
                firstName: "${agency.firstName}",
                lastName: "${agency.lastName}"
            }
            <c:if test="${!agencyStatus.last}">,</c:if>
            </c:forEach>
        ];
        var proofers = [

            <c:forEach items="${actionBean.proofers}" var="proofer" varStatus="prooferStatus">
            {
                value:"${proofer.userId} ${proofer.initials} ${proofer.firstName} ${proofer.lastName}",
                id: "${proofer.userId}",
                initial: "${proofer.initials}",
                firstName: "${proofer.firstName}",
                lastName: "${proofer.lastName}"
            }<c:if test="${!prooferStatus.last}">,</c:if>

            </c:forEach>
        ];

        var scopists = [

            <c:forEach items="${actionBean.scopists}" var="scopist" varStatus="scopistStatus">
            {
                value:"${scopist.userId} ${scopist.initials} ${scopist.firstName} ${scopist.lastName}",
                id: "${scopist.userId}",
                initial: "${scopist.initials}",
                firstName: "${scopist.firstName}",
                lastName: "${scopist.lastName}"
            }<c:if test="${!scopistStatus.last}">,</c:if>
            </c:forEach>
        ];
        var rateunits =[

                        <c:forEach items="${actionBean.ratePriceType}" var="rateunit" varStatus="rateunitsts">
                        { 
                            id: "${rateunit.id}",
                            type: "${rateunit.type}"
                        }<c:if test="${!rateunitsts.last}">,</c:if>
                        </c:forEach>
                        ];
             var perrateunits =[

                             <c:forEach items="${actionBean.ratUnitType}" var="rateunit" varStatus="rateunitsts">
                             { 
                                 id: "${rateunit.id}",
                                 type: "${rateunit.type}"
                             }<c:if test="${!rateunitsts.last}">,</c:if>
                             </c:forEach>
                             ];
     
     function callAjaxToCalculatePaymentAferJobSaving(jobId){
    	  

     	 $.ajaxSetup({
     		   jsonp: null,
     		   jsonpCallback: null
     		});

     	    $.ajax({
     		  type:'POST',
     		  url: 'qgl-log-detail-accounting.action?calculatePaymentForAJob',//name of action?name of method in action
     		  dataType: 'json',
     		  data: {jobId:jobId},
     			 
     		  success: function(result){
     			   
     			if(result!=null){
     				$("#receivableAmount"+jobId).html();
     				$("#receivableAmount"+jobId).html("$"+result.receivableAmount.toFixed(2));
     				$("#receivableAmount"+jobId).html();
     				$("#payableAmount"+jobId).html("$"+result.payableAmount.toFixed(2));
     				$("#prooferPayable"+jobId).html("$"+result.prooferPayable.toFixed(2));
     				$("#scopistPayable"+jobId).html("$"+result.scopistPayable.toFixed(2));
     				$("#netAmount"+jobId).html("$"+result.netAmount.toFixed(2));
     			}
          
     		 },
     		  error:function() { 
     			  
     		  }
     	});
     }
     
     
    	  function getAllReimbursedServices(jobId,id,type){
    	 	 $.ajaxSetup({
    			   jsonp: null,
    			   jsonpCallback: null
    			});
    	 	var value= document.getElementById(id).value;
			if(value == "false"){
				var reimid ='';
			  if(type == 'reim')
				  reimid = '#servicereimtext'+jobId;
			  else
				  reimid = '#servicenonreimtext'+jobId;
			  
			     $(reimid).html('No');
				return;
			}
			var reimid ='';
			 if(type == 'reim'){
				  reimid = '#servicereimtext'+jobId;
			 }else{
				  reimid = '#servicenonreimtext'+jobId;
			 }
			 $(reimid).html('<a href="javascript:{}" onclick="getAllReimbursedServices('+jobId+',\''+id+'\',\''+type+'\')">Yes</a>');
			 if($.trim($("#agencyId"+jobId).val()).length == 0 || $.trim($("#agencyId"+jobId).val()) =='0')
 				return;
			    var newcodes={code:new Array()}
				getUserMasterRateItems(jobId,type,newcodes,$("#agencyId"+jobId).val(),false);
    		    $.ajax({
    			  type:'POST',
    			  url: 'qgl-log-detail-accounting.action?getRateItemsFromJobService',
    			  dataType: 'json',
    			  data: {jobId:jobId,agencyId:$("#agencyId"+jobId).val(),type:type,typeId:$("#typeId"+jobId).val()},
    				 
    			  success: function(result){
    				  rateitemcount = 0;
    				  reqrtcodes = result[1];
    				 $("#servicesreimforminner").html("");
    				  var str = "<div id='allservicreimdiv'>";
    				  str +='<div id="allservicreimErrorMSGdiv" class="fontStyle"></div>';
    				str += "<fieldset>";
    			   	str += "<table id='servreimberstable' style='width:100%;text-align: center;'>";
					str += '<tbody><colgroup>';
					str += '<col width="1%">';
					str += '<col width="9%">';
				    str += '<col width="28%">';
				    str += '<col width="7%">';
					str += '<col width="7%">';
					str += '<col width="8%">';
					str += '<col width="10%">';
					str += '<col width="9%">';
					str += '<col width="6%">';
					str += '<col width="6%">';
					str += '<col width="8%">';
					str += '</colgroup>';
    			   	str += "<th>Select</th>";
    			   	str += "<th>Code</th>";
    			   	str += "<th>Description</th>";
    			   	str += "<th>Quantity</th>";
    				str += "<th>Count</th>";
    			   	str += "<th>Value</th>";
    			   	str += "<th>Unit</th>";
    			   	str += "<th>PerUnit</th>";
    			   	str += "<th>Reimbursable<br>";
    				str +="<input type='checkbox' class='checkboxAllReim-QGL' name='checkbox' value='checkbox' /></th>";
    			   	str += "<th>Taxable<br>";
    				str += "<input type='checkbox' class='checkboxAllTax-QGL' name='checkbox' value='checkbox' /></th>";
    			    str += "<th></th>"; 
    				str += "<tbody>"; 
    				
    	            if(result != null && result[0].length > 0){
    	         	   for(var i in result[0]){
    	         		   str += getNewRateItemRow(result[0][i],'new',$("#typeId"+jobId).val(),jobId,$("#agencyId"+jobId).val());
    	         		   
    	         	   }
    	            }
    	            str += "</tbody>"; 
    	            str += " </table>";
    	            str += "</fieldset>";
    	            str +='<div id="allservicreimErrorMSGdivOuter" class="fontStyle"></div>';
    	            str += "</div>";
    	            $("#servicesreimforminner").html(str);
    	            
    	            //var buttons = "<input type='button' onclick='getRatesForReimbursment("+jobId+",\""+type+"\")' value='Click To Add From Rate Table'></input> ";
    	            //var buttons = "<input type='button' class='addNewRowItemClass' onclick='addNewRowItem(\""+type+"\")' value='Add New '></input> ";
    		        //   buttons+= "<input type='button' onclick='getUserMasterRateItems("+jobId+",\""+type+"\")' value='Click To Add From Master Rate Table '></input> ";
    		         //  $("#ratetableview").html(buttons);
    	            if(type == 'reim'){
      	        	  
     	        	   $('#servicesreimform').dialog( "option", "title", 'Services Reimbursed');


     	           }else{
     	        	  
     	        	   $('#servicesreimform').dialog( "option", "title", 'Services Non-Reimbursed');


     	           }
                    
    	            $( "#servicesreimform").dialog({
    	                autoOpen: true,
    	                height: 450,
    	                width: 920,
    	                modal: true,
    	                open:function(){
     					   $(".reimjobrateitemcode").live("change",function(){
     							  var flag=ServhighlightDuplicates(".reimjobrateitemcode");
     							  if (!flag){
     							    serviceAutoPopulateMRItem($(this),type);
     							  }
     							});
     					   $(".servdelete").live("click",function(){
     					   	       //ServhighlightDuplicates(".reimjobrateitemcode");						 
     							}); 
     						$(".reimjobrateitemrateunit").live("change",function(){
     						   if($(this).val()==2)
     						   servicesReimexpedite(this);
     						});	
     						$(".reimjobrateitemperunit").live("focus",function(){
     						   if($(this).closest("tr").find(".reimjobrateitemrateunit").val()==2)
     						   	    servicesReimexpedite(this);
     						});
     						$(".reimjobrateitemperunit").closest("tbody").live("change",function(){
     								servicesReimexpedite(".reimjobrateitemrateunit");
     						
     						});
     					   },
    	                buttons: {
    	                	 "Add New": function() {
                      		   addNewRowItem(type);
                             },
                      	   "Click To Add From Master Rate Table": function() {
                      		   var codes={code:new Array()}
                  		       $(".rateitemclass").each(function() { 
                      		   if($("#jobrateitemid"+$(this).attr('id')).val() == '0' && $.trim($("#jobrateitemcode"+$(this).attr('id')).val()).length >0)
                      		   {
                      			   var obj1 = {};
                      			   obj1["rateItemCode"] = $("#jobrateitemcode"+$(this).attr('id')).val();
                      			   codes.code.push(obj1);
                      		   }
                      		  });
                  		      getUserMasterRateItems(jobId,type,codes,$("#agencyId"+jobId).val(),true);
                            },
                             Cancel: function() {
                                 $( this ).dialog( "close" );
                             },
                             "Apply Selected Code(s)": function() {
    	                 	   var reqVals = [];
    	                 	   $(".rateitemclass").each(function() {
    	                 		   reqVals.push($(this).attr('id'));
    	                 		});
    	                 	   var obj={
    	      	            			rateitems:new Array()
    	      	            			
    	      	            	}
    	      	            	obj["jobId"]=jobId;
    	                 	   obj["agencyId"]=$("#agencyId"+jobId).val();
    							   var eFlag = false;
    							   var str = '';
    							   var ccval = '';
    							   var actulPgs = '';
    							   
    	                 	  for(var k in reqVals){
    	                 		  var obj1 = {
    		                			};
    	                 		  
    	                 		 var code = $.trim($("#jobrateitemcode"+reqVals[k]).val());
                       		      if( (code == 'cc' || code == 'cC' || code == 'Cc' || code == 'CC') && $("#jobrateitemselected"+reqVals[k]).is(":checked")){
                       			     ccval = $("#jobrateitemquantity"+reqVals[k]).val();
                    			     actulPgs = $("#jobrateitemcount"+reqVals[k]).val();
                       		      }
    	                 		  obj1["jobselected"] = $("#jobrateitemselected"+reqVals[k]).is(":checked"); 
    	                 		  obj1["rateItemId"] = $("#jobrateitemid"+reqVals[k]).val();
    	                 		  obj1["rateItemCode"] = ($("#jobrateitemcode"+reqVals[k]).val()).toUpperCase();
    	                 		  obj1["rateItemDesc"] = $("#jobrateitemdesc"+reqVals[k]).val();
    	                 		  obj1["quantity"] = $("#jobrateitemquantity"+reqVals[k]).val();
    	                 		  obj1["rateItemCount"] =  $("#jobrateitemcount"+reqVals[k]).val();
    	                 		  obj1["value"] =  $("#jobrateitemprice"+reqVals[k]).val();
    	                 		  obj1["rateItemrateunit"] = $("#jobrateitemrateunit"+reqVals[k]).val();
    	                 		  obj1["rateItemperunit"] =  $("#jobrateitemperunit"+reqVals[k]).val();
    	                 		  obj1["reimbursable"] =  $("#jobrateitemreimb"+reqVals[k]).is(":checked");
    	                 		  obj1["taxable"] = $("#jobrateitemtaxabl"+reqVals[k]).is(":checked"); 
    	                 		 obj1["newratecode"] = $("#jobrateitemperunit"+reqVals[k]).find("option:selected").text();  
    								  if($.trim(obj1["rateItemCode"]) == "")
    								  {
    									  str +='Code is Required.';
    									  eFlag = true;
    									 
    								  }
    								  if($.trim(obj1["rateItemCount"]) == "")
    								  {
    									  str +='Count is Required.';
    									  eFlag = true;
    								  }
    								  if($.trim(obj1["quantity"]) == "")
    								  {
    									  str +='Quantity is Required.';
    									  eFlag = true;
    								  }
    								  if($.trim(obj1["value"]) == "")
    								  {
    									str +='Value is Required.';
    									eFlag = true;
    								  }
									  else if(isNaN(obj1["value"]))
									  {
										  str +='Enter Numeric Value.';
										  eFlag = true;
								      }
    								  $("#allservicreimErrorMSGdiv").html(str);
    								  if(eFlag)
    									  return;
    								  
    	       	            	  obj.rateitems.push(obj1);
    	       	            	}  
    	                 	  $.ajaxSetup({
    	    	          		   jsonp: null,
    	    	          		   jsonpCallback: null
    	    	          		});

    	    	          	    $.ajax({
    	    	          		  type:'POST',
    	    	          		  url: 'qgl-log-detail-accounting.action?saveJobServices',
    	    	          		  dataType: 'json',
    	    	          		  data: {data:JSON.stringify(obj),type:type},
    	    	          			 
    	    	          		  success: function(result){
    	    	          			  
    	    	          			if(result.length == 0){
               	          				$("#servicesreimform").dialog( "close" );
               	          			if(ccval.length > 0){
           	          			    	$("#ccVal"+jobId).val(parseInt(ccval)+1);
           	          			        $("#ccValView"+jobId).html(parseInt(ccval)+1);
               	          			  }
               	          		     if($.trim(actulPgs).length > 0){
               	          		      $("#actulPgs"+jobId).val(parseInt(actulPgs));
               	          		      $("#actulPgsView"+jobId).html(parseInt(actulPgs));
               	          		     }
               	          			    saveSelectedJob(jobId,true);
               	          			  }
               	          			  else{
               	          				$("#allservicreimErrorMSGdiv").html(result).addClass("errorblockdiv");
               	          			$("#allservicreimErrorMSGdivOuter").html(result).addClass("errorblockdiv");
               	          			  }
    	    	          		 },
    	    	          		  error:function() { 
    	    	          			  
    	    	          		  }
    	    	          	});	
    	                 		  
    	                 		  //$( this ).dialog( "close" );
    	                    }
    	                },
    	                close: function() {

    	                },
    	                create:function () {
    				        $(this).closest(".ui-dialog")
    				            .find(".ui-button") // the first button
    				            .addClass("p-button");
    				    }
    	            });
    	            
    	            
    	            
    			 },
    			  error:function() { 
    			
    			  }
    		});

    	 }
</script>

<link rel="stylesheet" media="all" type="text/css" href="${pageContext.request.contextPath}/css/jquery/overcast/jquery-ui-1.8.21.custom.css"></link>
		<!--<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/my-profile.css" />-->

<script type="text/javascript"
	src="${pageContext.request.contextPath}/js/jquery-ui.min-1.8.21.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/js/jquery-ui-timepicker-addon-1.0.1.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/js/jquery-ui-sliderAccess-1.0.1.js"></script>

	<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/qgl-log-pending.css" ></link>
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/qgl-log-detail.css" ></link>
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/qgl-dialog-buttons.css" />
<link type="text/css" rel="stylesheet"
	href="${pageContext.request.contextPath}/css/billing-invoice.css" ></link>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/qgl-log-detail-accounting.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/qgl-log-accounting.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		ajaxCallToGetMasterRateItems(1);
    	ajaxCallToGetMasterRateItems(2);
		$("#helpContent").hide();
		$(function() {
			$("#close").click(function() {
				$("#helpContent").hide(500);
			});
			$("#slidebutton").click(function() {
				$("#helpContent").show(500);
			});
		});
		$(".detailsLink").click(function() {
			//$(".edit-job").trigger("click");
			$("#detailAccounting").toggle(500);
		});
	});
</script>
<%-- basheers code added by srikanth end --%>
<style>
#masterTableInnerDiv select {width: 75px;}
.reimjobrateitemperunit {width: 75px;}
.reimjobrateitemrateunit {width: 75px;}
</style>